<!--
 * @Description: 你的代码我的心
 * @Author: GGB
 * @Date: 2021-12-24 14:08:47
 * @LastEditors: GGB
 * @LastEditTime: 2022-01-26 15:05:53
-->
<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="register" title="修改API">
    <!-- 表单信息 -->
    <BasicForm class="p-4" @register="formRegister">
      <template #apiIds="{ model, field }">
        <BasicTree
          checkable
          :selectedKeys="model[field]"
          :checkedKeys="model[field]"
          @check="(keys) => (model[field] = keys)"
          :treeData="treeData"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { apiFormSchemas } from './modalApi.data';
  import { bindApiMenu } from '/@/api/permission/menu';
  import { getApiList } from '/@/api/permission/api';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BindApiMenuParams, MenuFormParams } from '/@/api/permission/model/menuModel';
  import { ref } from 'vue';
  // 定义数据
  let reload = () => {};
  const treeData = ref<TreeItem[]>([]);
  const recordId = ref<number>(0);

  // 注册form
  const [formRegister, { getFieldsValue, setFieldsValue, resetFields }] = useForm({
    schemas: apiFormSchemas,
    layout: 'vertical',
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });

  // 初始化表单数据
  const [register, { closeModal, changeOkLoading }] = useModalInner(async (data) => {
    reload = data.reload;
    const { name, apiIds, menu_id } = data.record;
    const treeList = await getApiList({
      pageSize: 5000,
      page: 1,
    });
    //对list进行递归处理
    const list = treeList.list as any[];
    treeData.value = list.map((org) => mapTree(org));
    setFieldsValue({ name, apiIds });
    recordId.value = menu_id;
  });

  // 更改信息
  const handleOk = () => {
    let value = getFieldsValue() as MenuFormParams;
    delete value.name;
    let param = { form: value, menu_id: recordId.value } as BindApiMenuParams;
    changeOkLoading(true);
    const { createMessage } = useMessage();
    bindApiMenu(param)
      .then(({ code, message }) => {
        code === 0 && createMessage.success(message);
        reload();
        closeModal();
      })
      .catch(() => {
        createMessage.error('修改失败');
      })
      .finally(() => {
        changeOkLoading(false);
        resetFields();
      });
  };

  // 做数据进行处理
  const mapTree = (org) => {
    const haveChildren = Array.isArray(org.children) && org.children.length > 0;
    return {
      //分别将我们查询出来的值做出改变他的key
      title: org.name,
      value: org.api_id,
      key: org.api_id,
      //判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
      children: haveChildren ? org.children.map((i) => mapTree(i)) : [],
    };
  };
</script>
